<template>
  <el-dialog
    :close-on-click-modal="false"
    :title="title"
    :visible="visible"
    lock-scroll
    width="1200px"
    @close="close"
  >

    <section class="grid gap-6" style="grid-template-columns: 1fr 2fr">
      <el-form
        ref="form"
        :model="dataForm"
        :rules="dataFormRules"
        label-width="120px"
      >

        <el-form-item label="奖励类型" prop="type">
          <el-select v-model="dataForm.type" class="mr-4" clearable placeholder="请选择奖励类型">
            <el-option
              v-for="item in Object.keys(referenceTable)"
              :key="item"
              :label="referenceTable[item]"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="目标次数" prop="count">
          <el-input-number v-model="dataForm.count" :min="1"/>
        </el-form-item>

        <el-form-item label="任务描述" prop="desc">
          <el-input
            v-model="dataForm.desc"
            placeholder="请输入任务描述"
            type="textarea"
          />
        </el-form-item>

        <el-form-item label="是否显示" prop="is_visible">
          <el-radio-group v-model="dataForm.is_visible">
            <el-radio-button :label="1">显示</el-radio-button>
            <el-radio-button :label="0">隐藏</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <section>
        <el-form
          v-for="(item, index) in rewardList"
          :key="index"
          :model="item"
          :rules="rewardRules"
          label-width="120px"
        >
          <el-form-item label="奖励类型" prop="reward_type">
            <el-select v-model="item.reward_type" class="mr-4" clearable placeholder="请选择奖励类型">
              <el-option v-for="item in rewardType" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>

          <!--  礼物  -->
          <section v-show="item.reward_type === 'gift'">

            <el-form-item label="礼物名称" prop="reward_id">
              <el-select v-model="item.reward_id" clearable placeholder="请选择具体奖励">
                <el-option v-for="gift in giftList" :key="gift.id" :label="gift.name" :value="gift.id">
                  <section class="flex items-center justify-between">
                    <span>{{ gift.name }}</span>
                    <img :src="gift.picture" alt="" class="w-8 h-8">
                  </section>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="有效期" prop="count">
              <section class="flex items-center">
                <el-input-number v-model="item.count" :min="1" class="mr-4"/>
                <p class="mr-8">天</p>
              </section>
            </el-form-item>
          </section>

          <!-- 虚拟币 -->
          <section v-show="item.reward_type === 'coin'">

            <el-form-item label="数量" prop="count">
              <el-input-number v-model="item.count" :min="0" class="mr-4"/>
            </el-form-item>

          </section>

          <!-- 商品 -->
          <section v-show="item.reward_type === 'product'">

            <el-form-item label="奖励名称" prop="reward_id">
              <el-select v-model="item.reward_id" clearable placeholder="请选择具体奖励">
                <el-option v-for="product in productList" :key="product.id" :label="product.product_name"
                           :value="product.id"
                >
                  <section class="flex items-center justify-between">
                    <span>{{ product.product_name }}</span>
                    <img :src="product.picture" alt="" class="w-8 h-8">
                  </section>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="数量" prop="count">
              <el-input-number v-model="item.count" :min="0" class="mr-4"/>
            </el-form-item>
          </section>


          <el-form-item label="是否显示" prop="is_visible">
            <el-radio-group v-model="item.is_visible">
              <el-radio-button :label="1">显示</el-radio-button>
              <el-radio-button :label="0">隐藏</el-radio-button>
            </el-radio-group>
          </el-form-item>

          <section class="rings rings_save" @click="handleSave(item, index)">保存该奖励项</section>
          <section v-if="!item.is_database" class="rings rings_del" @click="toDelCurRing(index)">删除当前奖励项</section>
        </el-form>

        <hr>

        <section class="rings rings_add" @click="addNew">新增奖励项</section>
      </section>
    </section>


    <section slot="footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </section>
  </el-dialog>
</template>

<script>
import { referenceTable, rewardType } from '@/views/anchorReward/config'
import request from '@/utils/request'

const dialogTitle = {
  add: '新增',
  edit: '编辑'
}

const rules = {
  type: [{ required: true }],
  count: [{ required: true }],
  desc: [{ required: true }],
  is_visible: [{ required: true }]
}

const rewardRules = {
  reward_type: [{ required: true }],
  reward_id: [{ required: true }],
  count: [{ required: true }],
  is_visible: [{ required: true }]
}

export default {
  props: {
    refreshData: {
      type: Function,
      required: true
    }
  },
  data() {
    return {
      visible: false,
      rewardType,
      referenceTable,
      dataFormRules: rules,
      rewardRules,
      title: dialogTitle.add,
      dataForm: {
        id: undefined,
        type: '',
        count: 1,
        desc: '',
        is_visible: 1
      },
      rewardList: [
        {
          id: undefined,
          /*
          * 该条奖励是否存在于数据库中
          *   默认任务奖励数据无法被删除（没有提供删除接口） 只能修改 is_visible 软删除
          *   新增的没有添加到数据库的则可以在添加时进行删除
          *
          *   该字段仅前端使用，提交时删除该字段
          * */
          is_database: false,
          reward_type: '',
          reward_id: '',
          count: 0,
          is_visible: 1
        }
      ],
      giftList: [],
      productList: []
    }
  },
  computed: {
    form() {
      return this.$refs.form
    }
  },
  created() {
    this.initData()
  },
  methods: {
    /*
  * 初始化下拉数据
  * */
    async initData() {
      try {
        const { data: { data: giftList } } = await request({ url: '/gift/general-gift?sale_status=-1&page_size=100' })
        const { data: { data: productList } } = await request({ url: '/mall/product/list?cate_id=0&status=1&style_id=0&page=1&page_size=100' })

        this.giftList = giftList
        this.productList = productList
      } catch (e) {
        console.error(e)
      }
    },
    show(row) {
      if (row) {
        console.log(row)
        const { id, type, count, is_visible, desc, rewards } = row
        this.dataForm.id = id
        this.dataForm.type = type
        this.dataForm.count = count
        this.dataForm.is_visible = is_visible
        this.dataForm.desc = desc

        this.rewardList = rewards.map(reward => ({
          is_database: true,
          id: reward.id,
          reward_type: reward.type,
          reward_id: reward.reward_id,
          count: reward.count,
          is_visible: reward.is_visible
        }))

        this.title = dialogTitle.edit
      } else {
        this.title = dialogTitle.add
      }

      this.visible = true
    },

    /*
    * 确认操作
    * */
    async handleConfirm() {
      try {
        if (this.title === dialogTitle.edit) /* 编辑 */ {
          const id = this.dataForm.id
          const { code } = await request({
            url: `/presenter/task/template/${id}`,
            method: 'put',
            params: this.dataForm
          })
          if (code === 200) {
            this.$message.success('编辑成功')
          } else {
            // throw new Error('编辑失败')
          }
        } else if (this.title === dialogTitle.add) /* 新增 */ {
          const { code } = await request({
            url: '/presenter/task/template',
            method: 'post',
            data: this.dataForm
          })
          if (code === 200) {
            this.$message.success('创建成功')
          } else {
            throw new Error('创建失败')
          }
        }
        this.refreshData()
      } catch (e) {
        console.error(e)
      } finally {
        this.dataForm = {
          checkin_count: 1,
          reward_type: 'coin',
          reward_id: 1,
          count: 0,
          is_visible: 1,
          id: undefined
        }

        this.visible = false
      }
    },

    /*
    * 保存任务奖励
    * */
    async handleSave(reward, index) {

      let status
      const templateId = this.dataForm.id
      const tempData = JSON.parse(JSON.stringify(reward))
      delete tempData.id
      delete tempData.is_database

      if (reward.is_database) /* 编辑任务奖励 */ {
        const rewardId = reward.id
        const { code } = await request({
          url: `/presenter/task/template/${templateId}/reward/${rewardId}`,
          method: 'put',
          data: tempData
        })
        status = code
      } else  /* 新增任务奖励 */  {
        console.log(reward)
        const { code } = await request({
          url: `/presenter/task/template/${templateId}/reward`,
          method: 'post',
          data: tempData
        })
        status = code
        reward.is_database = true
      }

      if (status === 200) {
        this.$message.success('操作成功')
      } else {
        this.$message.error('操作失败')
      }
    },

    close() {
      this.dataForm = {
        id: undefined,
        type: '',
        count: 1,
        desc: '',
        is_visible: 1
      }
      
      this.visible = false
      this.refreshData()
    },

    addNew() {
      this.rewardList.push({
        is_database: false,
        reward_type: '',
        reward_id: '',
        count: 0,
        is_visible: 1
      })
    },

    toDelCurRing(index) {
      this.rewardList.splice(index, 1)
    }
  }
}
</script>


<style lang="scss" scoped>
.rings {
  height         : 30px;
  line-height    : 30px;
  text-align     : center;
  letter-spacing : 1em;
  width          : 90%;
  margin         : 1em auto;
  cursor         : pointer;
  user-select    : none;
  border         : none;

  &_save {
    border : 1px dashed #78c8f3;
    color  : #78c8f3;
  }

  &_add {
    border : 1px dashed green;
    color  : green;
  }

  &_del {
    border : 1px dashed #de1717;
    color  : #de1717;
  }
}


</style>
